public class Leetcode953 {
    public static void main(String[] args) {
        System.out.println(isAlienSorted(new String[]{"apple", "app"}, "abcdefghijklmnopqrstuvwxyz"));
    }

    public static boolean isAlienSorted(String[] words, String order) {
        int[] orderIndexMap = new int[26];
        char[] wordsChars = order.toCharArray();
        for (int i = 0; i < wordsChars.length; i++) {
            orderIndexMap[wordsChars[i] - 'a'] = i;
        }

        for (int i = 0; i < words.length - 1; i++) {
            if (!check(words[i], words[i + 1], orderIndexMap)) {
                return false;
            }
        }

        return true;
    }

    private static boolean check(String a1, String a2, int[] rules) {
        char[] a1Char = a1.toCharArray();
        char[] a2Char = a2.toCharArray();

        int maxLength = Math.max(a1Char.length, a2Char.length);
        for (int i = 0; i < maxLength; i++) {
            if (a1Char.length <= i || a2Char.length <= i) {
                return a1.length() < a2.length();
            }


            if (a1Char[i] == a2Char[i]) {
                continue;
            }

            return rules[a1Char[i] - 'a'] <= rules[a2Char[i] - 'a'];
        }

        return true;
    }
}
